<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Exceptions\InvalidRequestException;
use App\Models\Labor;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class DingService
{
    // 钉钉API基础地址
    protected $baseUrl = 'https://oapi.dingtalk.com';

    /**
     * 获取访问令牌
     * 缓存2小时（钉钉access_token有效期）
     */
    public function getAccessToken($ding_key,$ding_secret)
    {
        $ding_secret = Crypt::decryptString($ding_secret);
        return Cache::remember('dingtalk_access_token', 120, function () use ($ding_key,$ding_secret) {
            $response = Http::get("{$this->baseUrl}/gettoken", [
                'appkey' => $ding_key,
                'appsecret' => $ding_secret,
            ]);

            $result = $response->json();

            if (isset($result['errcode']) && $result['errcode'] !== 0) {
                throw new \Exception("获取access_token失败: {$result['errmsg']}");
            }

            return $result['access_token'];
        });
    }

    /**
     * 获取用户打卡记录
     *
     * @param array $userIds 用户ID列表
     * @param string $startDate 开始日期（格式：YYYY-MM-DD）
     * @param string $endDate 结束日期（格式：YYYY-MM-DD）
     * @return array 打卡记录
     */
    public function getAttendanceRecords($ding_key,$ding_secret,array $userIds, string $startDate, string $endDate)
    {
        $accessToken = $this->getAccessToken($ding_key,$ding_secret);

        // 转换日期格式为时间戳（毫秒）
        $response = Http::post("{$this->baseUrl}/attendance/listRecord?access_token={$accessToken}", [
            'userIds' => $userIds,
            'checkDateFrom' => $startDate,
            'checkDateTo' => $endDate,
        ]);

        $result = $response->json();

        if (isset($result['errcode']) && $result['errcode'] !== 0) {
            throw new \Exception("获取打卡记录失败: {$result['errmsg']}");
        }

        return $result['recordresult'] ?? [];
    }

    /**
     * 获取部门用户列表（用于获取userid）
     */
    public function getDeptUsers($ding_key,$ding_secret,$dept_id,int $offset = 0, int $size = 100)
    {
        $accessToken = $this->getAccessToken($ding_key,$ding_secret);

        $response = Http::get("{$this->baseUrl}/topapi/v2/user/list", [
            'access_token' => $accessToken,
            'offset' => $offset,
            'dept_id' => $dept_id,
            'size' => $size,
            'cursor' => 0,
        ]);

        $result = $response->json();

        if (isset($result['errcode']) && $result['errcode'] !== 0) {
            throw new \Exception("获取部门用户失败: {$result['errmsg']}");
        }

        return $result['result'] ?? [];
    }

    /**
     * 获取部门列表
     */
    public function getDept($ding_key,$ding_secret,int $offset = 0, int $size = 100)
    {
        $accessToken = $this->getAccessToken($ding_key,$ding_secret);

        $response = Http::get("{$this->baseUrl}/topapi/v2/department/listsub", [
            'access_token' => $accessToken,
        ]);

        $result = $response->json();

        if (isset($result['errcode']) && $result['errcode'] !== 0) {
            throw new \Exception("获取部门用户失败: {$result['errmsg']}");
        }

        return $result['result'] ?? [];
    }
}
